package org.gdstash.character;

import org.gdstash.file.GDReader;
import org.gdstash.file.GDWriter;
import org.gdstash.util.FileVersionException;
import org.gdstash.util.GDMsgFormatter;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class GDCharNoteList {
    private static final int VERSION = 1;
    private static final int BLOCK = 12;
    private int version;
    private List<String> notes;

    public GDCharNoteList() {
        this.notes = new LinkedList<String>();
    }

    public void read() throws IOException {
        int val = 0;
        final GDReader.Block block = new GDReader.Block();
        val = GDReader.readBlockStart(block);
        if (val != 12) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        this.version = GDReader.readEncInt(true);
        if (this.version != 1) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        this.notes.clear();
        val = GDReader.readEncInt(true);
        for (int i = 0; i < val; ++i) {
            final String note = GDReader.readEncString();
            this.notes.add(note);
        }
        GDReader.readBlockEnd(block);
    }

    public void write() throws IOException {
        final GDReader.Block block = new GDReader.Block();
        GDWriter.writeBlockStart(block, 12);
        GDWriter.writeInt(this.version);
        final int val = this.notes.size();
        GDWriter.writeInt(val);
        for (final String note : this.notes) {
            GDWriter.writeString(note);
        }
        GDWriter.writeBlockEnd(block);
    }

    public int getByteSize() {
        int size = 0;
        size += 4;
        size += 4;
        size += 4;
        size += 4;
        for (final String note : this.notes) {
            size += 4;
            if (note != null) {
                size += note.length();
            }
        }
        size += 4;
        return size;
    }
}
